#include <vector>
class Solution {
    int dx[4] = {0, 0, -1, 1};
    int dy[4] = {-1, 1, 0, 0};
    bool vis[1005][1005];
    vector<int> path;
    int maxlen = 0, m, n;
public:
    void dfs(vector<vector<int>>& matrix, vector<int>& path, int i, int j, int len) {
        if (path.size() == m*n) {
            maxlen = m*n;
            return;
        }
        vis[i][j] = true;
        path.push_back(vis[i][j]);
        for (int k = 0; k < 4; ++k) {
            int x = i + dx[k];
            int y = j + dy[k];
            if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y]) {
                if (matrix[x][y] > matrix[i][j]) {
                    dfs(matrix, path, x, y, len+1);         
                } else {
                    maxlen = max(maxlen, len);
                }
            }
        }
        vis[i][j] = false;
        path.pop_back();
    }
    int solve(vector<vector<int>>& matrix) {
        m = matrix.size();
        n = matrix[0].size();
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                dfs(matrix, path, i, j, 1);
            }
        }
        return maxlen;
    }
};